package com.wxxymakers.grademark.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wxxymakers.grademark.exception.ServiceException;
import com.wxxymakers.grademark.model.entity.WxCollege;
import com.wxxymakers.grademark.model.mapper.WxCollegeMapper;
import com.wxxymakers.grademark.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * @AUTHOR soft
 * @DATE 2018/12/27 17:49
 * @DESCRIBE
 */
@Service
public class WxCollageService {

    @Autowired
    private WxCollegeMapper collegeMapper;

    @Transactional
    public boolean add(WxCollege college) {
        if (byName(college.getName()) != null) {
            throw new ServiceException("学院已存在！");
        }
        return collegeMapper.insert(college) > 0;
    }

    @Transactional
    public boolean delete(int id) {
        return collegeMapper.deleteById(id) > 0;
    }

    @Transactional
    public boolean change(WxCollege college) {
        return collegeMapper.updateById(college) > 0;
    }

    public WxCollege byId(int id) {
        return collegeMapper.selectById(id);
    }

    public WxCollege byName(String name) {
        WxCollege college = new WxCollege();
        college.setName(name);
        return collegeMapper.selectOne(new QueryWrapper<>(college));
    }

    public Page<WxCollege> page(int page, int limit, WxCollege query) {
        QueryWrapper<WxCollege> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");

        if (query != null) {
            if (!StringUtils.isEmpty(query.getName())) wrapper.like("name", query.getName());
        }
        Integer total = collegeMapper.selectCount(wrapper);
        if (total > 0) {
            IPage<WxCollege> iPage = collegeMapper.selectPage(PageUtils.rowBounds(page, limit), wrapper);
            return new PageImpl<>(iPage.getRecords(), new PageRequest(page - 1, limit), total);
        }
        return null;
    }
}
